package io.sdl.modules.sys.controller;

import cn.hutool.core.date.DateTime;


import io.sdl.common.annotation.LogOperation;
import io.sdl.common.constant.Constant;
import io.sdl.common.constant.UrlConstants;
import io.sdl.common.page.PageData;
import io.sdl.common.utils.*;
import io.sdl.common.validator.AssertUtils;
import io.sdl.common.validator.ValidatorUtils;
import io.sdl.common.validator.group.AddGroup;
import io.sdl.common.validator.group.DefaultGroup;
import io.sdl.common.validator.group.UpdateGroup;
import io.sdl.modules.security.user.SecurityUser;
import io.sdl.modules.security.user.UserDetail;
import io.sdl.common.sys.dto.SdlInstitutionDTO;
import io.sdl.common.sys.dto.SdlInstitutionQaqDTO;
import io.sdl.modules.sys.excel.SdlInstitutionQaqExcel;
import io.sdl.common.sys.service.SdlInstitutionQaqService;
import io.sdl.common.sys.service.SdlInstitutionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;


/**
 * @author Dc 1211734836@qq.com
 * @since 1.0.0 2025-03-28
 */
@RestController
@RequestMapping("sdl/institutionqaq")
@Tag(name = "")
public class SdlInstitutionQaqController {
    @Autowired
    private SdlInstitutionQaqService sdlInstitutionQaqService;

    @Autowired
    private SdlInstitutionService sdlInstitutionService;

    @GetMapping("page")
    @Operation(summary = "分页")
    @Parameters({
            @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
            @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String")
    })
    @RequiresPermissions("sdl:institutionqaq:page")
    public Result<PageData<SdlInstitutionQaqDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {

        PageData<SdlInstitutionQaqDTO> page = sdlInstitutionQaqService.page(params);
        page.getList().forEach(e->{
            SdlInstitutionDTO sdlInstitutionDTO = sdlInstitutionService.getbyId(e.getInstitutionId());
            e.setInstitutionName(sdlInstitutionDTO.getInstitutionName());
            e.setCertificateFile(UrlConstants.getProductionUrl() + e.getCertificateFile());
        });
        return new Result<PageData<SdlInstitutionQaqDTO>>().ok(page);
    }


    @GetMapping("manage")
    @Operation(summary = "资质列表")
    @Parameters({
            @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
            @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String")
    })
    @RequiresPermissions("sdl:institutionqaq:manage")
    public Result<PageUtils> getManage(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        Integer total = sdlInstitutionQaqService.getNum(query);
        List<SdlInstitutionQaqDTO> list = sdlInstitutionQaqService.getManageByInstitutionId(query);
        PageUtils pageUtil = new PageUtils(list, total, query.getLimit(), query.getPage());

        return new Result<PageUtils>().ok(pageUtil);

    }

    @GetMapping("{id}")
    @Operation(summary = "信息")
    @RequiresPermissions("sdl:institutionqaq:info")
    public Result<SdlInstitutionQaqDTO> get(@PathVariable("id") Long id) {
        SdlInstitutionQaqDTO data = sdlInstitutionQaqService.get(id);

        return new Result<SdlInstitutionQaqDTO>().ok(data);
    }


    @GetMapping("list/{id}")
    @Operation(summary = "信息列表")
    @RequiresPermissions("sdl:institutionqaq:infoList")
    public Result<PageData<SdlInstitutionQaqDTO>> getInfoList(@PathVariable("id") Long id) {

        List<SdlInstitutionQaqDTO> qaqDTOList = sdlInstitutionQaqService.getQaqListByInstitutionId(id);
        PageData<SdlInstitutionQaqDTO> page = new PageData<>(qaqDTOList, qaqDTOList.size());

        return new Result<PageData<SdlInstitutionQaqDTO>>().ok(page);
    }

    @PostMapping
    @Operation(summary = "保存")
    @LogOperation("保存")
    @RequiresPermissions("sdl:institutionqaq:save")
    public Result save(@RequestBody SdlInstitutionQaqDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        UserDetail user = SecurityUser.getUser();
        dto.setCreateTime(DateTime.now());
        dto.setCreater(user.getId());
        dto.setIsDel(1);
        dto.setQualificationIsvalidity(1);
        dto.setIsShow(1);
        dto.setIsExamine(0);
        String result = String.join(",", dto.getCertificateFilesList());
        dto.setCertificateFile(result);
        sdlInstitutionQaqService.save(dto);

        return new Result();
    }

    @PutMapping
    @Operation(summary = "修改")
    @LogOperation("修改")
    @RequiresPermissions("sdl:institutionqaq:update")
    public Result update(@RequestBody SdlInstitutionQaqDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        sdlInstitutionQaqService.update(dto);

        return new Result();
    }

    @DeleteMapping("{id}")
    @Operation(summary = "删除")
    @LogOperation("删除")
    @RequiresPermissions("sdl:institutionqaq:delete")
    public Result delete(@PathVariable("id") Long id) {
        //效验数据
//        AssertUtils.isArrayEmpty(id, "id");

        sdlInstitutionQaqService.deleteById(id);

        return new Result();
    }

    @GetMapping("export")
    @Operation(summary = "导出")
    @LogOperation("导出")
    @RequiresPermissions("sdl:institutionqaq:export")
    public void export(@Parameter(hidden = true) @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<SdlInstitutionQaqDTO> list = sdlInstitutionQaqService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "", list, SdlInstitutionQaqExcel.class);
    }


    @PostMapping("upload/image")
    @Operation(summary = "证书上传")
    @LogOperation("证书上传")
//    @RequiresPermissions("")
    public Result fileUpload(@RequestParam("file") MultipartFile file) throws Exception {

        if (file.isEmpty()) {
            return new Result().error("文件有误");
        }
        return new Result().ok("/uploads/" + UploadFileUtils.uploadFile(file));

    }


    @PostMapping("submit/examine")
    @Operation(summary = "证书审核")
    @LogOperation("证书审核")
    @RequiresPermissions("sdl:institutionqaq:examine")
    public Result submitExamine(@RequestBody SdlInstitutionQaqDTO dto) throws Exception {

        dto.setExaminer(SecurityUser.getUserId());
        dto.setExamineData(DateTime.now());
        sdlInstitutionQaqService.submitExamine(dto);
        return new Result();
    }

}
